<template>
  <main-card-admin title="学校组织管理" :loading="loading" :main-body-style-obj="{ paddingTop: '32px' }">
    <template #tool-btn>
      <a-button type="primary" @click="addAndEdit('新增组织')">新增组织</a-button>
    </template>
    <template #screen-space>
      <a-input v-model:value="pageForm.orgName" v-trim allow-clear class="w-328" placeholder="请输入组织名称" @keyup.enter="getTree()">
        <template #suffix>
          <i class="iconfont icon-search-line"></i>
        </template>
      </a-input>
    </template>

    <div class="content">
      <!-- :scroll="{ x: 1650, y: 594 }" -->
      <a-table class="table" row-key="id" :indent-size="24" :columns="columns" :pagination="false" :data-source="dataList">
        <template #expandIcon="{ expanded, onExpand, record }">
          <template v-if="record.children.length">
            <img
              class="expand-icon"
              :src="expanded ? expandIconDown : expandIconRight"
              alt=""
              @click="
                e => {
                  onExpand(record, e)
                }
              "
            />
          </template>
        </template>

        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'level'">
            {{ filterLevel(record.level) }}
            <!-- {{ record.level }} -->
          </template>
          <template v-else-if="column.dataIndex === 'tools'">
            <div class="tools-box">
              <!-- v-if="record.isAuthActive" -->
              <a-dropdown v-if="record.isAuthActive">
                <!-- <a-button type="link">更多</a-button> -->
                <a-button type="text" class="icon-only-btn" @click.stop>
                  <i class="iconfont icon-more-line"></i>
                </a-button>
                <template #overlay>
                  <a-menu>
                    <a-menu-item v-if="record.level !== 1" key="0" @click="addAndEdit('编辑组织', record as DataItem)">
                      <a href="javascript:;">编辑</a>
                    </a-menu-item>
                    <a-menu-item v-if="record.level !== 5" key="1" @click="addAndEdit('添加子级', record as DataItem)">
                      <a href="javascript:;">添加子级</a>
                    </a-menu-item>
                    <a-menu-item v-if="record.level !== 1" key="2" @click="del(record as DataItem)">
                      <a href="javascript:;">删除</a>
                    </a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
            </div>
          </template>
          <template v-else>
            {{ replaceEmptyStr(record[column.dataIndex as string]) }}
          </template>
        </template>
      </a-table>
    </div>
    <!-- </div> -->
  </main-card-admin>
  <addAndEditModal
    v-if="addAndEditShow"
    :id="addAndEditId"
    :title="title"
    :add-child-id="addChildId"
    :open="addAndEditShow"
    @ok="addAndEditDone"
    @cancel="addAndEditCancel"
  />
</template>

<script setup lang="ts">
  import { message, Modal } from 'ant-design-vue'
  import { computed, onMounted, ref } from 'vue'

  import expandIconDown from '@/assets/img/caret-down.svg'
  import expandIconRight from '@/assets/img/caret-right.svg'
  import { schoolOrganizationManageApi } from '@/services/api/aigc-admin'
  import { replaceEmptyStr } from '@/utils'

  import addAndEditModal from '../components/addAndEdit.vue'
  import { DataItem } from '../types/index'
  const pageForm = ref({
    orgName: ''
  })
  const dataList = ref<any>([])
  const loading = ref<boolean>(false)
  // 获取树形数据
  const getTree = async (): Promise<void> => {
    loading.value = true
    const { data } = await schoolOrganizationManageApi.list(pageForm.value)
    dataList.value = data
    console.log('获取树形数据:', dataList.value)

    loading.value = false
  }

  const columns = [
    {
      title: '组织名称',
      dataIndex: 'orgName',
      width: 1012
    },
    {
      title: '类型',
      dataIndex: 'level',
      width: 200
    },
    {
      title: '教师人数',
      dataIndex: 'teacherCount',
      width: 200
    },
    {
      title: '学生人数',
      dataIndex: 'studentCount',
      width: 200
    },
    {
      title: '',
      dataIndex: 'tools'
    }
  ]
  // 1：学校 2：学院 3：专业 4：学级 5:班级
  const filterLevel = (val: number) => {
    switch (val) {
      case 1:
        return '学校'

      case 2:
        return '学院'

      case 3:
        return '专业'

      case 4:
        return '学级'

      case 5:
        return '班级'

      default:
        break
    }
  }
  // 校验通过后的删除弹框
  const delCofirm = async (val: string) => {
    Modal.confirm({
      title: '确定删除?',
      content: '选择的学校组织将被删除，且不可恢复，请确认',
      okText: '删除',
      cancelText: '取消',
      onOk: async () => {
        const res = await schoolOrganizationManageApi.del(val)()
        if (res.code === 'SYSTEM-100000') {
          message.success('删除成功')
          getTree()
        }
        console.log('OK', res)
      },
      onCancel() {
        console.log('Cancel')
      }
    })
  }
  // 校验失败后的提示弹框
  const errorModal = () => {
    // Modal.confirm({
    //   title: '删除失败',
    //   content: '请在组织下的教师和学生人数均为0后，重试此操作',
    //   icon: createVNode(ErrorIcon),
    //   okText: '',
    //   cancelText: '确定'
    // })
    Modal.error({
      title: '删除失败',
      content: '请在组织下的教师和学生人数均为0后，重试此操作',
      okText: '确定'
    })
  }
  // 操作按钮方法
  const del = (record: DataItem) => {
    if ((record?.teacherCount as number) > 0 || (record?.studentCount as number) > 0) {
      errorModal()
    } else {
      delCofirm(record?.id)
    }
  }

  // 编辑新增
  const addAndEditShow = ref<boolean>(false)
  const addAndEditId = ref<string>()
  const addChildId = ref<string>()
  const title = ref<string>('')
  const addAndEdit = (code: string, record?: DataItem) => {
    if (code === '添加子级') {
      addChildId.value = record?.id
      // addAndEditId.value = ''
    }
    if (code === '编辑组织') {
      addAndEditId.value = record?.id
      // addChildId.value = ''
    }

    addAndEditShow.value = true
    title.value = code
  }
  const addAndEditDone = () => {
    getTree()
    addAndEditId.value = ''
    addChildId.value = ''
    addAndEditId.value = ''
    addAndEditShow.value = false
  }
  const addAndEditCancel = () => {
    addAndEditId.value = ''
    addChildId.value = ''
    addAndEditId.value = ''
    addAndEditShow.value = false
  }
  const scrollX = computed(() => {
    return columns.reduce((prev, curr) => {
      return prev + (curr.width as number)
    }, 0)
  })
  onMounted(() => {
    getTree()
  })
</script>

<style lang="less" scoped>
  :deep(.ant-table-body) {
    &::-webkit-scrollbar {
      overflow-y: auto;
      width: 4px;
      height: 4px;
    }

    &::-webkit-scrollbar-thumb {
      background: #c5c5c7;
      border-radius: 5px;
    }

    &::-webkit-scrollbar-track {
      background: #f1f1f1;
    }

    &::-webkit-scrollbar-thumb:hover {
      background: #949496; /* 鼠标悬停时滑块颜色 */
    }
  }

  .expand-icon {
    cursor: pointer;
    vertical-align: middle;
    margin-right: 5.5px;
  }

  .test-page {
    position: relative;
    display: flex;
    padding: 32px;
    height: 100%;
    min-height: 0;
    background: #fff;
    border-radius: 8px;
    flex-direction: column;

    .title-wrap {
      font-size: 22px;
      color: rgba(21, 23, 27, 0.95);
      font-weight: 700;
      line-height: 28px;
      flex-shrink: 0;
    }

    .tool {
      display: flex;
      margin: 24px 0 12px;
      flex-shrink: 0;

      .btn-right {
        display: flex;
        margin-left: auto;
        gap: 0 8px;
      }
    }

    .content {
      padding-bottom: 52px;
      width: 100%;
      min-height: 0;
      border-radius: 8px;

      .table {
      }

      .tools-box {
        display: flex;
        gap: 0 16px;

        .item {
          color: rgba(0, 156, 248, 1);
          cursor: pointer;
        }
      }
    }
  }

  .batch-bottom {
    position: absolute;
    bottom: 0;
    left: 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 36px;
    width: 1672px;
    background: #fff;
    box-shadow: 0 -1px 0 0 rgba(37, 37, 45, 0.12);

    .btn-left {
      display: flex;
      gap: 0 32px;
      align-items: center;

      .action {
        color: rgba(51, 176, 249, 1);
        cursor: pointer;
      }

      .devide-line {
        width: 1px;
        height: 36px;
        background-color: #e8e9eb;
      }
    }

    .tips-right {
      display: flex;
      gap: 0 4px;
      color: rgba(17, 22, 31, 0.52);
    }
  }
</style>
